<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { localCache } from '@/utils/storage'
import { useRouter } from 'vue-router'
import useUser from '@/store/user'
// 获取路由跳转
const router = useRouter()
const userInfo = reactive({
  user: localCache.getCache('user') ?? '',
  password: localCache.getCache('password') ?? ''
})
const user = useUser()
// 记住密码
const submitForm = () => {
  elFormEl.value?.validate((validate) => {
    if (validate) {
      // 验证通过根据 账号密码获取token
      user
        .getterUserTokenAysnc({
          username: userInfo.user,
          password: userInfo.password
        })
        .then((res) => {
          user.user.name = res.username
          user.user.avatar = res.avatar
          user.user.menu = res.routes
          // 跳转到home页
          router.push('/main')
        })
      // 记住密码
      if (localCache.getCache('rmPassword')) {
        localCache.setCache('user', userInfo.user)
        localCache.setCache('password', userInfo.password)
      }
    } else {
      alert('验证失败')
    }
  })
}

defineExpose({
  submitForm
})
const elFormEl = ref<FormInstance>()
const rulesUser = reactive({
  user: [
    { required: true, message: 'Please input user name', trigger: 'blur' },
    { min: 3, max: 10, message: 'Length should be 3 to 10', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' }
  ]
})
elFormEl
</script>

<template>
  <div class="user">
    <el-tab-pane label="User" name="user">
      <template #label>
        <span class="icon">
          <el-icon><UserFilled /></el-icon>
        </span>
        User
      </template>
      <div class="user">
        <el-form
          label-position="left"
          :model="userInfo"
          label-width="80px"
          size="large"
          status-icon
          :rules="rulesUser"
          ref="elFormEl"
        >
          <el-form-item label="user" prop="user">
            <el-input v-model="userInfo.user" />
          </el-form-item>
          <el-form-item label="password" prop="password">
            <el-input
              v-model="userInfo.password"
              type="password"
              show-password
            />
          </el-form-item>
        </el-form>
      </div>
    </el-tab-pane>
  </div>
</template>

<style scoped></style>
